<?php

// +----------------------------------------------------------------------
// | Http 工具类
// | 提供一系列的Http方法
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace yicmf\tools;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\MessageTrait;
use GuzzleHttp\Psr7\Response;
use think\Exception;

class HttpClient
{


    protected $param = '';
    protected $query = '';
    protected $contentType = '';

    /**
     * @var Client
     */
    protected $client;
    /**
     * @var  Response
     */
    protected $response;
    /**
     * @var static
     */
    protected static $instance;

    /**
     * @param $base_uri
     * @param array $headers
     * @param int $timeout
     */
    public function __construct($base_uri, array $headers = [], int $timeout = 30, $verify = true)
    {
        $headers_default = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0',
        ];
        $headers = array_merge($headers_default, $headers);
        $this->client = new Client([
            'base_uri' => $base_uri,
            'timeout' => $timeout,
            'headers' => $headers,
            'allow_redirects' => false,
            'verify' => $verify,
            'cookies' => true// 默认启用自动cookie，需要一次性请求
        ]);
    }

    /**
     * 实例化
     * @param $base_uri
     * @param array $header
     * @param int $timeout
     * @return static
     */
    public static function instance($base_uri, array $header = [], int $timeout = 30): HttpClient
    {
        return new static($base_uri, $header, $timeout);
    }

    /**
     * 传参
     * https://guzzle-cn.readthedocs.io/zh-cn/latest/quickstart.html#id9
     * @param $param
     * @param string $contentType = 'json'|'form_params'|'body'|'multipart'
     * @return $this
     */
    public function param($param, string $contentType = 'json')
    {
        $this->param = $param;
        $this->contentType = $contentType;
        return $this;
    }

    /**
     * 传参
     * @return $this
     */
    public function query($query)
    {
        $this->query = $query;
        return $this;
    }

    /**
     * 模拟post发起请求
     * $headers = [
     * 'Authorization' => '4283A7F1244D4172Axxxxxx',
     * ];
     * $http = MyHttpService::instance('域名',$headers);
     *
     * $cc = $http->param(['dsa'=>1,'da'=>22])->post('/post');
     * try {
     *  dump($cc->parseContent());
     * } catch (\Exception $e) {
     * }
     * @param string $uri
     * @param array $headers
     * @return $this
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function post(string $uri = '', array $headers = [])
    {
        $this->response = $this->client->request('POST', $uri, [
            $this->contentType => $this->param,
            'headers' => $headers
        ]);
        return $this;
    }

    /**
     * 模拟GET发起请求
     * HttpClient::instance('http://ot.jfshou.cn')->query($param)->get('/privilege-api/express/delivery/auth/index');
     * @param string $uri
     * @param array $headers
     * @return $this
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function get(string $uri = '', array $headers = [])
    {

        $this->response = $this->client->request('GET', $uri, [
            'query' => $this->query,
            'headers' => $headers
        ]);
        return $this;
    }

    /**
     * 获取响应头信息
     * @param string $name
     * @return array|string
     */
    public function getHeader(string $name = '')
    {
        $field = [];
        foreach ($this->response->getHeaders() as $index => $values) {
            if (count($values) == 1) {
                $field[$index] = $values[0];
            } else {
                $field[$index] = $values;
            }
        }
        if ($name) {
            if (isset($field[$name])) {
                return $field[$name];
            } else {
                return false;
            }
        } else {
            return $field;
        }
    }

    /**
     * 解析响应数据
     * @param bool $parseJson
     * @return mixed
     * @throws Exception
     */
    public function parseContent(bool $parseJson = true)
    {
        // 解析响应数据
        if ($this->response->getStatusCode() == 200) {
            $content = $this->response->getBody()->getContents();
            if ($parseJson) {
                return json_decode($content, true);
            } else {
                return $content;
            }
        } else {
            throw new Exception($this->response->getReasonPhrase(), $this->response->getStatusCode());
        }
    }

    /**
     * 解析响应数据
     * @param bool $parseJson
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }

}//类定义结束
